<template>
  <div class="container">
    <div class="app-container" />
    <el-tree :data="depts" :props="defaultProps" :default-expand-all="true" :highlight-current="true" @node-click="handleNodeClick">
      <template #default="{data}">
        <el-row justify="space-between" style="width: 100%" align="middle">
          <el-col :span="20">{{ data.name }}</el-col>
          <el-col :span="4">
            <el-row justify="space-between" align="middle">
              <el-col :span="12">{{ data.managerName || '无' }}</el-col>
              <el-col :span="12">
                <el-dropdown @command="handleCommand($event,data.id)">
                  <span class="el-dropdown-link">
                    下拉菜单<i class="el-icon-arrow-down el-icon--right" />
                  </span>
                  <el-dropdown-menu slot="dropdown">
                    <el-dropdown-item command="add">黄金糕</el-dropdown-item>
                    <el-dropdown-item command="edit">狮子头</el-dropdown-item>
                    <el-dropdown-item command="delete">螺蛳粉</el-dropdown-item>
                  </el-dropdown-menu>
                </el-dropdown>
              </el-col>
            </el-row>
          </el-col>
        </el-row>
      </template>
    </el-tree>
    <el-dialog :visible.sync="showDialog" :title="title" @close="close">
      <el-form ref="Form" label-width="100px" :model="addForm" :rules="rules">
        <el-form-item label="部门名称" prop="name">
          <el-input v-model="addForm.name" placeholder="请输入" />
        </el-form-item>
        <el-form-item label="部门编码" prop="code">
          <el-input v-model="addForm.code" placeholder="请输入" />
        </el-form-item>
        <el-form-item label="部门负责人" prop="managerId">
          <el-select v-model="addForm.managerId" placeholder="请输入">
            <el-option v-for="item in managerList" :key="item.id" :label="item.username" :value="item.id" />
          </el-select>
        </el-form-item>
        <el-form-item label="部门介绍" prop="introduce">
          <el-input v-model="addForm.introduce" type="textarea" placeholder="请输入" />
        </el-form-item>
      </el-form>
      <div style="display: flex;justify-content: center;">
        <el-button type="primary" @click="btnOk">确定</el-button>
        <el-button @click="close">取消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>

import { transListToTreeData } from '@/utils'
import { getDepartmentListApi, getEmployeeSimpleApi, addDepartmentApi, getDepartDetail, deleteDepartment, editDepartment } from '@/api/department'
export default {
  name: 'Department',
  data() {
    return {
      managerList: [],
      addForm: {
        name: '',
        code: '',
        managerId: '',
        introduce: ''
      },
      list: [],
      parentId: null,
      rules: {

        name: [
          { required: true, message: '请输入部门名称', trigger: 'blur' },
          { min: 2, max: 10, message: '长度在 2 到 10 个字符', trigger: 'blur' },
          {
            validator: (rule, value, callback) => {
              let temp = this.list
              temp = temp.filter(item => item.id !== this.addForm.id)

              if (temp.some(item => item.name === value)) {
                callback(new Error('部门名称已存在'))
              } else {
                callback()
              }
            },
            trigger: 'blur'
          }

        ],
        //   业务校验
        code: [
          { required: true, message: '请输入部门编码', trigger: 'blur' },
          { min: 2, max: 10, message: '长度在 2 到 10 个字符', trigger: 'blur' },
          {
            validator: (rule, value, callback) => {
              let temp = this.list
              temp = temp.filter(item => item.id !== this.addForm.id)
              if (temp.some(item => item.code === value)) {
                callback(new Error('部门编码已存在'))
              } else {
                callback()
              }
            },
            trigger: 'blur'
          }

        ],
        managerId: [
          { required: true, message: '请选择部门负责人', trigger: 'blur' }
        ],
        introduce: [
          { required: true, message: '请输入部门介绍', trigger: 'blur' },
          { min: 1, max: 100, message: '长度在 1 到 100 个字符', trigger: 'blur' }
        ]

      },
      showDialog: false,
      depts: [],

      defaultProps: {
        label: 'name',
        children: 'children'
      }
    }
  },
  computed: {
    title() {
      return this.addForm.id ? '编辑部门' : '添加部门'
    }
  },
  created() {
    this.getDepartments()
    this.getEmployeeSimple()
  },
  methods: {
    async getDepartments() {
      const result = await getDepartmentListApi()
      // console.log('1', this.departmentTree(result, 1))
      this.list = result
      this.depts = transListToTreeData(result, 0)
    },
    // 编辑
    async getDepartDetail() {
      const res = await getDepartDetail(this.parentId)
      console.log(res)
      this.addForm = res
    },
    // 删除
    async deleteDepartment() {
      await deleteDepartment(this.parentId)
    },
    handleCommand(type, id) {
      if (type === 'add') {
        this.showDialog = true
        this.parentId = id
      } else if (type === 'edit') {
        this.showDialog = true
        this.parentId = id
        this.getDepartDetail()
      } else {
        this.$confirm('此操作将永久删除该文件, 是否继续?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(async() => {
          this.parentId = id
          this.deleteDepartment()
          this.$message('删除成功')
          this.getDepartments()
        }).catch(() => {
          this.$message({
            type: 'info',
            message: '已取消删除'
          })
        })
      }
    },
    // 获取负责人
    async getEmployeeSimple() {
      const res = await getEmployeeSimpleApi()
      this.managerList = res
    },
    btnOk() {
      this.$refs.Form.validate(async isOk => {
        if (isOk) {
          if (this.addForm.id) {
            await editDepartment(this.addForm)
            this.$message('编辑成功')
          } else {
            this.$message('添加成功')
            await addDepartmentApi({ ...this.addForm, pid: this.parentId })
          }
          this.close()
          this.getDepartments()
          this.getDepartmentListApi()
        }
      })
    },
    close() {
      this.$refs.Form.resetFields()
      this.showDialog = false
      this.addForm = {
        name: '',
        code: '',
        managerId: '',
        introduce: ''
      }
    }

  }
}
</script>
<style>

</style>
